function newTag()
{
  var name = $('#newTag').val();

  if (name !== '') {
    window.location = 'tag/new/' + name + '/';
  }
}

function addTag()
{
  var tag = $('#tag').val(), vehicle = $('#vehicle').val();

  window.location = 'tag/add/' + tag + '/' + vehicle + '/';
}

function updatePositions()
{
  // Launch Ajax query to retrieve the current list of positions
  $.getJSON(
    '/track/ajax/positions/',
    // This function is executed once the ajax query completes
    function(data)
    {
      // data is an array that associates ids to two-element arrays
      $.each(
        data,
        function(id)
        {
          // For each element in the data array (i.e. for each vehicle)
          // we have and [x, y] array :
          // vehicle === id, x === this[0], y === this[1]
          $('#vehicle-' + id + '-x').html(String(this[0]));
          $('#vehicle-' + id + '-y').html(String(this[1]));
          $('#vehicle-' + id + '-checkpoint').html(String(this[2]));
          $('#vehicle-' + id + '-advancement').html(String(this[3]));
        });
      
      // We have finished updating positions for all vehicles, we can update
      // the "last position retrieval" date in the interface
      var currentTime = new Date();
      
      $('#updateTime').html(
        currentTime.getHours()
        + 'h' + currentTime.getMinutes()
        + ':' + currentTime.getSeconds()
        + '.' + currentTime.getMilliseconds());
      
      // We wait for 300ms before launching a new ajax query
      setTimeout(updatePositions, 300);
    });
}

$(function()
{
  $.getJSON(
    '/track/ajax/vehicles/',
    function(data)
    {
      var table = '<table><tr><th>Name</th><th>x</th><th>y</th><th>Checkpoint</th><th>Advancement</th></tr>';

      $.each(
        data,
        function(id)
        {
          table +=
            '<tr>'
            + '<td>'
              + this.name
            + '</td>'
            + '<td id="vehicle-' + id + '-x"></td>'
            + '<td id="vehicle-' + id + '-y"></td>'
            + '<td id="vehicle-' + id + '-checkpoint"></td>'
            + '<td id="vehicle-' + id + '-advancement"></td>'
          + '</tr>';
        });

      table += '</table>';

      $('#vehicles').html(table)

      updatePositions();
    });
});
